package com.springboot.yangspringboot;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import java.util.Map;

public class YangSpringApplication {
    public static void run(Class clazz) {
//        创建一个Spring 容器 这就是新建一个容器方式
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
//       注册进去一个类，clazz相当于内部spring容器的配置类
        applicationContext.register(clazz);
        applicationContext.refresh();
//        startTomcat(applicationContext);

        WebServer webServer = getWebServer(applicationContext);
        webServer.start(applicationContext);
    }

    private static WebServer getWebServer(WebApplicationContext applicationContext) {
//        这个是到Spring 容器里面拿对象，对应之前启动的时候，有哪些服务放到当前的spring 容器里面
//        key bean 的名字，value bean的对象
        Map<String, WebServer> beansOfType = applicationContext.getBeansOfType(WebServer.class);
        if (beansOfType.isEmpty()) {
            throw new RuntimeException("there is no server!");
        }
        if (beansOfType.size() > 1) {
            throw new RuntimeException("there are two servers!");
        }
        return beansOfType.values().stream().findFirst().get();
    }


}
